﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DataAccess;
using System.Collections;
using System.Data.SqlClient;
using System.Reflection;

namespace QLDSVCNTT_Nhom1
{
    public partial class frmQLSinhVien : Form
    {
        public frmQLSinhVien()
        {
            InitializeComponent();
        }

        public static string tenhe;
        public void tabThietLap(int i)
        {
            this.tabCtr.SelectedTabIndex = i;
        }
        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public void KhoaText()
        {
            txtMaLop.Enabled = false;
            txtTenLop.Enabled = false;
            txtSL.Enabled = false;
            txtGVCN.Enabled = false;
            btnThem.Enabled = true;
            btnLuu.Enabled = false;
            btnXoa.Enabled = false;
            btnSua.Enabled = false;
        }
        public void Reset()
        {
            txtMaLop.Text = "";
            txtTenLop.Text = "";
            txtSL.Text = "";
            txtGVCN.Text = "";
        }
        public void ResetSV()
        {
            txtMSSinhVien.Text = "";
            txtHoTenSV.Text = "";
            dtpNgaySinh.Value = DateTime.Now;
        }
        public void MoText()
        {
            txtMaLop.Enabled = true;
            txtTenLop.Enabled = true;
            //txtSL.Enabled = false;
            txtGVCN.Enabled = true;
            btnThem.Enabled = false;
            btnLuu.Enabled = true;
            btnXoa.Enabled = false;
            btnSua.Enabled = false;
        }

        private void frmQLSinhVien_Load(object sender, EventArgs e)
        {
            KhoaText();
            LoadTree(tvLop);

            List<string> find = new List<string> { "-- All --", "MSSV", "Ho", "Ten" };
            cbbFind.ComboBox.DataSource = find;
            cbbFind.ComboBox.SelectedIndex = 0;
            lvDSLop.Visible = false;
            lvQLLop.Visible = false;
        }

        public void LoadTree(TreeView tv)
        {
            tv.Nodes.Clear();
            List<He> list = He.All();
            if (list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    TreeNode node = new TreeNode();
                    node.Text = list[i].TenHe.ToString();

                    List<Lop> data = Lop.TimLopTheoHe(list[i].MaHe);
                    if (data.Count > 0)
                    {
                        for (int j = 0; j < data.Count; j++)
                            node.Nodes.Add(data[j].TenLop.ToString());
                    }

                    tv.Nodes.Add(node);
                }
            }
            tv.ExpandAll();
        }

        private void tvLop_AfterSelect(object sender, TreeViewEventArgs e)
        {
            int mahe, malop, sl = 0;
            Lop lop = new Lop();
            try     //he:
            {
                tenhe = tvLop.SelectedNode.Parent.Text;
                string tenlop = tvLop.SelectedNode.Text;
                lop = Lop.TimLopTheoTen(tenlop);
                txtMaLop.Text = lop.MaLop.ToString();
                txtTenLop.Text = lop.TenLop;
                lvQLLop.Visible = true;
                lvDSLop.Visible = false;
                List<SinhVien> list = SinhVien.LayDSTheoLop(lop.MaLop);
                foreach (SinhVien sv in list)
                    sl++;
                txtSL.Text = sl.ToString();
                if (list.Count > 0)
                    BindLVSinhVien(list);
                else lvQLLop.Items.Clear();

                KhoaText();
                btnXoa.Enabled = true;
                btnSua.Enabled = true;
                btnThem.Enabled = false;

            }   //lop:
            catch (Exception)
            {
                tenhe = tvLop.SelectedNode.Text;
                mahe = He.LayMaHe(tenhe);
                List<Lop> listLop = Lop.TimLopTheoHe(mahe);

                lvQLLop.Visible = false;
                lvDSLop.Visible = true;
                Reset();
                BindLVLop(listLop);
                btnThem.Enabled = true;
                KhoaText();
            }
        }

        private void BindLVSinhVien(List<SinhVien> list)
        {
            lvQLLop.Items.Clear();
            foreach (SinhVien sv in list)
            {
                ListViewItem lvi = new ListViewItem(sv.MSSV);
                lvi.SubItems.Add(sv.HoTen);
                lvi.SubItems.Add(sv.GioiTinh ? "Nam" : "Nữ");
                lvi.SubItems.Add(sv.NgaySinh.ToString("mm/dd/yyyy"));
                lvi.SubItems.Add(sv.Lop);
                lvQLLop.Items.Add(lvi);
            }
        }
        private void BindLVLop(List<Lop> list)
        {
            lvDSLop.Items.Clear();
            foreach (Lop l in list)
            {
                int sl = 0;
                ListViewItem lvi = new ListViewItem(l.MaLop);
                lvi.SubItems.Add(l.TenLop);
                List<SinhVien> listSV = SinhVien.LayDSTheoLop(l.MaLop);
                foreach (SinhVien sv in listSV)
                    sl++;
                lvi.SubItems.Add(sl.ToString());
                lvDSLop.Items.Add(lvi);
            }
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            Reset();
            MoText();
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            if (txtSL.Text.Equals(""))
                txtSL.Text = "0";
            Lop lop = new Lop();
            lop.MaLop = txtMaLop.Text;
            lop.TenLop = txtTenLop.Text;

            try     //Sua
            {
                tenhe = tvLop.SelectedNode.Parent.Text;
                int mahe = He.LayMaHe(tenhe);
                List<Lop> listLop = Lop.TimLopTheoHe(mahe);
                if (KiemTraKhiLuu())
                {
                    lop = new Lop(txtMaLop.Text, txtTenLop.Text, mahe);
                    int rs = Lop.CapNhatLop(lop);
                    if (rs > 0)
                        MessageBox.Show("Sua thanh cong!");
                }
                BindLVLop(listLop);

            }
            catch (Exception)   //Them
            {
                tenhe = tvLop.SelectedNode.Text;
                int mahe = He.LayMaHe(tenhe);
                List<Lop> listLop = Lop.TimLopTheoHe(mahe);
                if (KiemTraKhiLuu())
                {
                    lop = new Lop(txtMaLop.Text, txtTenLop.Text, mahe);
                    int rs = Lop.ThemLop(lop);
                    if (rs > 0)
                        MessageBox.Show("Them lop thanh cong!");
                }
                BindLVLop(listLop);
            }
            frmQLSinhVien_Load(sender, e);
        }

        private bool KiemTraKhiLuu()
        {
            if (txtMaLop.Text == "")
            {
                MessageBox.Show("Chua nhap ma lop");
                return false;
            }
            if (txtTenLop.Text == "")
            {
                MessageBox.Show("Chua nhap ten lop");
                return false;
            }
            return true;
        }

        private void btnSua_Click(object sender, EventArgs e)
        {
            MoText();

        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Ban muon xoa lop nay ra khoi danh sach?", "Xác nhận",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                string tenlop = tvLop.SelectedNode.Text;
                Lop l = Lop.TimLopTheoTen(tenlop);
                int rs = Lop.XoaLop(l.MaLop);
                if (rs > 0)
                    MessageBox.Show("Xoa thanh cong !");
            }
            frmQLSinhVien_Load(sender, e);

        }

        private void txtSL_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsNumber(e.KeyChar) && !char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        private void lvQLLop_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            lvQLLop.ListViewItemSorter = new ListViewItemComparer(e.Column);
        }

        private void lvDSLop_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                ListViewItem lvi = lvDSLop.SelectedItems[0];
                txtMaLop.Text = lvi.SubItems[0].Text;
                txtTenLop.Text = lvi.SubItems[1].Text;
                txtSL.Text = lvi.SubItems[2].Text;
            }
            catch (System.Exception ex)
            {

            }
        }

        string LayHo(string hoten)
        {
            string ht = hoten.Trim();
            return ht.Substring(0, ht.Length);
        }
        string LayTen(string hoten)
        {
            string ht = hoten.Trim();
            return ht.Substring(ht.LastIndexOf(' ') + 1);
        }
        private void btnFind_Click(object sender, EventArgs e)
        {
            string timkiem = txtFind.Text;
            if (cbbFind.ComboBox.SelectedIndex == 2)
                timkiem = LayHo(txtFind.Text);
            else if (cbbFind.ComboBox.SelectedIndex == 3)
                timkiem = LayTen(txtFind.Text);
            List<SinhVien> list = SinhVien.TimKiem(timkiem, cbbFind.ComboBox.SelectedIndex);
            BindLVSinhVien(list);
        }


        private void btnQLSV_Click(object sender, EventArgs e)
        {
            tabCtr.SelectedTab = tiQLSV;
            lblTenLop.Text = "Lớp : " + txtTenLop.Text;
            List<SinhVien> list = SinhVien.LayDSTheoLop(txtMaLop.Text);

            DataTable dt = toDataTable(list);
            dgvSinhVien.DataSource = dt;

            //dgvSinhVien.DataSource = list;
            //dgvSinhVien.CellValueChanged += new DataGridViewCellEventHandler(dgvSinhVien_CellValueChanged);
        }

        //void dgvSinhVien_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        //{
        //    //DataGridViewRow row = dgvSinhVien.SelectedRows[0];
        //    DataGridViewRow drow = dgvSinhVien.Rows[e.RowIndex];
        //    object mssv = drow.Cells[1].Value;
        //    for (int i = 0; i < e.RowIndex; i++)
        //    {
        //        if (dgvSinhVien.Rows[i].Cells[1].Value.ToString() == mssv.ToString())
        //            MessageBox.Show("Da co sinh vien nay!!", "Invalid value");

        //        //xoa dong dang nhap:
        //        //dgvSinhVien.Rows.Remove(drow);
        //        break;
        //    }

        //}

        private void btnExit_Click(object sender, EventArgs e)
        {
            tabCtr.SelectedTab = tiQLLop;
        }

        private void dgvSinhVien_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Ban chua nhap day du du lieu cho cac cot !", "Invalid value");
            e.Cancel = true;    //bo wwa loi + giu  nguyen dl vua nhap
        }

        private void dgvSinhVien_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            //them vao stt:
            dgvSinhVien.Rows[e.RowIndex].Cells["SoTT"].Value = e.RowIndex + 1;
        }

        private void dgvSinhVien_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                txtMSSinhVien.Text = dgvSinhVien.SelectedRows[0].Cells[1].Value.ToString();
                txtHoTenSV.Text = dgvSinhVien.SelectedRows[0].Cells[2].Value.ToString();
                bool gt = (bool)dgvSinhVien.SelectedRows[0].Cells[3].Value;
                if (gt)
                    rdNam.Checked = true;
                else rdNu.Checked = true;
                dtpNgaySinh.Text = (dgvSinhVien.SelectedRows[0].Cells[4].Value.ToString());
            }
        }

        private void btnSuaSV_Click(object sender, EventArgs e)
        {
            if (txtMSSinhVien.Text != "" && txtHoTenSV.Text != "")
            {
                if (dtpNgaySinh.Value.ToShortDateString() == DateTime.Now.ToShortDateString())
                {
                    MessageBox.Show("vui lòng chọn ngày tháng!");
                    return;
                }
                bool gt = true;
                if (rdNu.Checked == true)
                    gt = false;
                string malop = txtMaLop.Text;
                SinhVien sv = new SinhVien(txtMSSinhVien.Text, txtHoTenSV.Text, gt, dtpNgaySinh.Value, malop);

                int rs = SinhVien.CapNhatSinhVien(sv);
                if (rs > 0)
                {
                    DataTable dt = (DataTable)dgvSinhVien.DataSource;
                    DataRow row = dt.NewRow();
                    row["MSSV"] = txtMSSinhVien.Text;
                    row["HoTen"] = txtHoTenSV.Text;
                    row["GioiTinh"] = true;
                    if (rdNu.Checked)
                        row["GioiTinh"] = false;
                    row["NgaySinh"] = dtpNgaySinh.Value;
                    row["Lop"] = txtMaLop.Text;
                    dt.Rows.Add(row);
                    MessageBox.Show("Cap nhat sinh vien thanh cong!");
                }
                else
                    MessageBox.Show("Khong the cap nhat sinh vien nay!");
            }
            else
                MessageBox.Show("vui lòng nhập đầy đủ thông tin");
        }

        private void tbnThemSV_Click(object sender, EventArgs e)
        {
            if (txtMSSinhVien.Text != "" && txtHoTenSV.Text != "")
            {
                if (dtpNgaySinh.Value.ToShortDateString() == DateTime.Now.ToShortDateString())
                {
                    MessageBox.Show("vui lòng chọn ngày tháng!");
                    return;
                }
                bool gt = true;
                if (rdNu.Checked == true)
                    gt = false;
                string malop = txtMaLop.Text;
                SinhVien sv = new SinhVien(txtMSSinhVien.Text, txtHoTenSV.Text, gt, dtpNgaySinh.Value, malop);

                int rs = SinhVien.ThemSinhVien(sv);
                if (rs > 0)
                {
                    DataTable dt = (DataTable)dgvSinhVien.DataSource;
                    DataRow row = dt.NewRow();
                    row["MSSV"] = txtMSSinhVien.Text;
                    row["HoTen"] = txtHoTenSV.Text;
                    row["GioiTinh"] = true;
                    if (rdNu.Checked)
                        row["GioiTinh"] = false;
                    row["NgaySinh"] = dtpNgaySinh.Value;
                    row["Lop"] = txtMaLop.Text;
                    dt.Rows.Add(row);
                    MessageBox.Show("Them sinh vien thanh cong!");
                }
                else
                    MessageBox.Show("Khong the them moi sinh vien!");
            }
            else
                MessageBox.Show("vui lòng nhập đầy đủ thông tin");
        }

        private void btnXoaSV_Click(object sender, EventArgs e)
        {
            string mssv = dgvSinhVien.CurrentRow.Cells[1].Value.ToString();
            if (MessageBox.Show("Ban co chac muon xoa sinh vien nay?", "Thong bao", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                int rs = SinhVien.XoaSinhVien(mssv);
                if (rs > 0)
                {
                    int rowIndex = dgvSinhVien.CurrentRow.Index;
                    dgvSinhVien.Rows.RemoveAt(rowIndex);
                    MessageBox.Show("Xoa thanh cong!");
                }
                else MessageBox.Show("Xoa khong thanh cong!");
            }
        }

        private void btnIn_Click(object sender, EventArgs e)
        {
            ExportToExcel excel = new ExportToExcel();
            DataTable dt = (DataTable)dgvSinhVien.DataSource;
            excel.Export(dt, "danh sach", "Danh sách sinh viên");
        }

        static DataTable toDataTable(List<SinhVien> list)
        {
            DataTable dt = null;
            if (list == null)
                return dt;
            Type listType = list.GetType();

            if (listType.IsGenericType)
            {
                Type elementType = listType.GetGenericArguments()[0];
                dt = new DataTable(elementType.Name + "List");
                MemberInfo[] miArray = elementType.GetMembers(BindingFlags.Public | BindingFlags.Instance);
                foreach (MemberInfo mi in miArray)
                {
                    if (mi.MemberType == MemberTypes.Property)
                    {
                        PropertyInfo pi = mi as PropertyInfo;
                        Type type = pi.PropertyType;
                        dt.Columns.Add(pi.Name, Nullable.GetUnderlyingType(type) ?? type);
                    }
                    else if (mi.MemberType == MemberTypes.Field)
                    {
                        FieldInfo fi = mi as FieldInfo;
                        dt.Columns.Add(fi.Name, fi.FieldType);
                    }
                }
                IList il = list;
                foreach (object record in il)
                {
                    int i = 0;
                    object[] fieldValues = new object[dt.Columns.Count];
                    foreach (DataColumn c in dt.Columns)
                    {
                        MemberInfo mi = elementType.GetMember(c.ColumnName)[0];
                        if (mi.MemberType == MemberTypes.Property)
                        {
                            PropertyInfo pi = mi as PropertyInfo;
                            fieldValues[i] = pi.GetValue(record, null);
                        }
                        else if (mi.MemberType == MemberTypes.Field)
                        {
                            FieldInfo fi = mi as FieldInfo;
                            fieldValues[i] = fi.GetValue(record);
                        }
                        i++;
                    }
                    dt.Rows.Add(fieldValues);
                }
            }
            return dt;
        }



    }


    public class ListViewItemComparer : IComparer
    {
        private int colm = -1;

        public ListViewItemComparer()
        {
            colm = 0;
        }
        public ListViewItemComparer(int p)
        {
            // TODO: Complete member initialization
            this.colm = p;
        }

        public int Compare(object x, object y)
        {
            int kq;
            ListViewItem lX = (ListViewItem)x;
            ListViewItem lY = (ListViewItem)y;
            switch (colm)
            {
                case 0:     //cot MSSV
                    int x1 = Convert.ToInt32(lX.SubItems[colm].Text);
                    int y1 = Convert.ToInt32(lY.SubItems[colm].Text);
                    if (x1 == y1)
                        kq = 0;
                    else if (x1 > y1)
                        kq = 1;
                    else kq = -1;
                    break;
                default:    //theo chuoi
                    kq = string.Compare(lX.SubItems[colm].Text, lY.SubItems[colm].Text) >= 0 ?
                        string.Compare(lX.SubItems[colm].Text, lY.SubItems[colm].Text) :
                        string.Compare(lY.SubItems[colm].Text, lX.SubItems[colm].Text);
                    break;
            }
            return kq;
        }
    }

}
